package com.cqcvc.controller;

import com.alibaba.fastjson.JSON;
import com.cqcvc.config.Result;
import com.cqcvc.entity.Permission;
import com.cqcvc.service.PermissionService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hunter
 * @since 2022-08-04
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    //@RequiresPermissions("permission:select")
    @GetMapping("/select")
    @ApiOperation(value = "查询所有菜单信息")
    public String selectPermission(String permissionName,Integer isMenu){
        List<Permission> list=permissionService.selectPermission(permissionName,isMenu);
        //找出一级菜单
        List<Permission> parentNode=list.stream().filter(permission -> permission.getFatherId()==0).collect(Collectors.toList());
        //找出一级菜单对应的子菜单
        for(Permission perm:parentNode){
            perm.setChildren(list.stream().filter(permission -> perm.getPermissionId().equals(permission.getFatherId())).collect(Collectors.toList()));
        }

        Map<String,Object> map=new HashMap<>();
//        List<Map<String,Object>> mapList=new ArrayList<>();
//        for(Permission permission:parentNode){
//            Map<String,Object> map1=new HashMap<>();
//            map1.put("permission",permission);
//            mapList.add(map1);
//        }
//        map.put("list",mapList);
        map.put("list",parentNode);
        return JSON.toJSONString(new Result().setCode(200).setData(map));
    }

    @RequiresPermissions("permission:save")
    @PostMapping("/save")
    @ApiOperation("添加新菜单")
    public String savePermission(@RequestBody Permission permission){
        int id=permissionService.savePermission(permission);
        return JSON.toJSONString(new Result().setCode(200).setMessage("成功保存菜单信息！"));
    }

    @RequiresPermissions("Permission:del")
    @GetMapping("/del")
    @ApiOperation("删除菜单")
    public String delPermission(Integer id) {
        int i = permissionService.delPermission(id);
        if (i > 0) {
            return JSON.toJSONString(new Result().setCode(200).setMessage("成功删除菜单信息！"));
        } else {
            return JSON.toJSONString(new Result().setCode(500).setMessage("删除用户菜单失败！"));
        }
    }

    @RequiresPermissions("permission:batchDel")
    @PostMapping("/batchDel")
    @ApiOperation("批量删除菜单")
    public String batchDelPermission(@RequestBody List<Integer> ids) {
        int i=permissionService.batchDelPermission(ids);
        return JSON.toJSONString(new Result().setCode(200).setMessage("批量删除菜单信息成功！"));
    }

}
